'use client'
import { useEffect } from 'react'

export default function TokenSaver({
  children
}: {
  children: React.ReactNode
}) {
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const url = new URL(window.location.href)
      const params = url.searchParams
      const token = params.get('console_token')
      const token2 = params.get('refresh_token')
      const isInternalJump = params.get('isInternalJump')

      if (token) {
        localStorage.setItem('console_token', token)
        localStorage.setItem('refresh_token', token2 || '')
        // 如果是系统内的跳转，则头部的导航栏不显示
        if (isInternalJump)
          localStorage.setItem('isInternal_jump', isInternalJump)

        // 删除 token 参数
        params.delete('console_token')
        params.delete('refresh_token')
        params.delete('isInternal_jump')

        url.searchParams.delete('console_token')
        url.searchParams.delete('refresh_token')
        url.searchParams.delete('isInternal_jump')

        const cleanUrl = url.origin + url.pathname + url.hash
        window.location.replace(cleanUrl)
      }
    }
  }, [])
  return <>{children}</>
}
